package queues

import (
	"context"
	"encoding/json"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/silenceper/wechat/v2/miniprogram/subscribe"
	"hotgo/internal/consts"
	"hotgo/internal/library/queue"
	"hotgo/internal/library/wechat"
	"hotgo/internal/model/entity"
	"hotgo/internal/service"
	"hotgo/utility/convert"
)

func init() {
	queue.RegisterConsumer(AfterVerified)
}

var AfterVerified = &qAfterVerified{}

type qAfterVerified struct{}

func (q *qAfterVerified) GetTopic() string {
	return consts.QueueAfterVerifiedTopic
}

func (q *qAfterVerified) Handle(ctx context.Context, mqMsg queue.MqMsg) error {
	var memberInfo entity.AdminMember

	if err := json.Unmarshal(mqMsg.Body, &memberInfo); err != nil {
		glog.Warningf(context.Background(), "AfterVerified Handle Unmarshal err: %s", err.Error())
		return nil
	}
	conf, err := service.SysConfig().GetSubMsg(ctx)
	if err != nil {
		glog.Warningf(context.Background(), "AfterVerified GetSubMsg err: %s", err.Error())
		return nil
	}
	if err = wechat.SendSubMsg(ctx, &subscribe.Message{
		ToUser:     memberInfo.OpenId,
		TemplateID: conf.MpRetainKey,
		Page:       conf.MpRetainPage,
		Data: map[string]*subscribe.DataItem{
			"name1":   {Value: memberInfo.Nickname},
			"thing11": {Value: conf.MpRetainContent},
		},
		MiniprogramState: convert.ConvertMpEnvCfg(g.Cfg().MustGet(ctx, "system.envVersion", "trial").String()),
		Lang:             "zh_CN",
	}); err != nil {
		glog.Warningf(ctx, "推送订阅消息失败: %s", err.Error())
	}
	return nil
}
